package com.ysx.service.Impl;

import com.ysx.dao.BlogDao;
import com.ysx.dao.CommentDao;
import com.ysx.entity.Blog;
import com.ysx.entity.Comment;
import com.ysx.entity.Mail;
import com.ysx.entity.User;
import com.ysx.service.CommentService;
import com.ysx.utils.MailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 博客评论业务层接口实现类
 */
@Service
public class CommentServiceImpl implements CommentService {

    @Resource
    private CommentDao commentDao;

    @Resource
    private BlogDao blogDao;
    @Autowired
    private MailUtil mailUtil;


    // 自动导入Java邮件发送实现类
    @Resource
    private JavaMailSender javaMailSender;

    //存放迭代找出的所有子代的集合
    private List<Comment> tempReplys = new ArrayList<>();

    /**
     * @Description: 查询评论
     * @Param: blogId：博客id
     * @Return: 评论消息
     */
    @Override
    public List<Comment> listCommentByBlogId(Long blogId) {
        //查询出父节点
        List<Comment> comments = commentDao.findByBlogIdParentIdNull(blogId, Long.parseLong("-1"));
        for (Comment comment : comments) {
            Long id = comment.getId();
            String parentNickname1 = comment.getNickname();
            List<Comment> childComments = commentDao.findByBlogIdParentIdNotNull(blogId, id);
            //查询出子评论
            combineChildren(blogId, childComments, parentNickname1);
            comment.setReplyComments(tempReplys);
            tempReplys = new ArrayList<>();
        }
        return comments;
    }


    /**
     * @Description: 查询出子评论
     * @Param: childComments：所有子评论
     * @Param: parentNickname1：父评论姓名
     * @Return:
     */
    private void combineChildren(Long blogId, List<Comment> childComments, String parentNickname1) {
        //判断是否有一级子评论
        if (childComments.size() > 0) {
            //循环找出子评论的id
            for (Comment childComment : childComments) {
                String parentNickname = childComment.getNickname();
                childComment.setParentNickname(parentNickname1);
                tempReplys.add(childComment);
                Long childId = childComment.getId();
                //查询出子二级评论
                recursively(blogId, childId, parentNickname);
            }
        }
    }

    /**
     * @Description: 循环迭代找出子集回复
     * @Param: chileId:子评论id
     * @Param: parentNickname1:子评论姓名
     * @Return:
     */
    private void recursively(Long blogId, Long childId, String parentNickname1) {
        //根据子一级评论的id找到子二级评论
        List<Comment> replayComments = commentDao.findByBlogIdAndReplayId(blogId, childId);

        if (replayComments.size() > 0) {
            for (Comment replayComment : replayComments) {
                String parentNickname = replayComment.getNickname();
                replayComment.setParentNickname(parentNickname1);
                Long replayId = replayComment.getId();
                tempReplys.add(replayComment);
                recursively(blogId, replayId, parentNickname);
            }
        }
    }

    //新增评论
    @Override
    public int saveComment(Comment comment, Comment parentComment) {
        comment.setCreateTime(new Date());
        int comments = commentDao.saveComment(comment);
//        文章评论计数
        blogDao.getCommentCountById(comment.getBlogId());

//         判断是否有父评论，有的话就发送邮件
//        if(parentComment!=null){
//            String parentNickname = parentComment.getNickname();
//            String nickName = comment.getNickname();
//            String title =blogDao.getTitleById(comment.getBlogId());
//            String comtent = "亲爱的" + parentNickname + "，您在【YanHuSuo博客】这篇"+title+"文章的评论收到了来自" + nickName + "博主的回复！内容如下：" + "\r\n" + "\r\n" +  comment.getContent();
//            String parentEmail = parentComment.getEmail();
//
//            // 发送邮件
//            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//            simpleMailMessage.setSubject("YanHuSuoの客栈评论回复");  //主题
//            simpleMailMessage.setText(comtent);   //内容
//            simpleMailMessage.setTo(parentEmail); //接收者的邮箱
//            simpleMailMessage.setFrom("983022332@qq.com");//发送者邮箱
//            javaMailSender.send(simpleMailMessage);
//        }
//        if(comment.getParentComment().getId()==-1){
//            String parentNickname = comment.getNickname();
//            String nickName = comment.getNickname();
//            String title =blogDao.getTitleById(comment.getBlogId());
//            String comtent = "亲爱的" + parentNickname + "，您在【YanHuSuo博客】这篇"+title+"文章的评论收到了来自" + nickName + "博主的回复！内容如下：" + "\r\n" + "\r\n" +  comment.getContent();
//            String parentEmail = comment.getEmail();
//
//            // 发送邮件
//            SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
//            simpleMailMessage.setSubject("YanHuSuoの客栈评论回复");  //主题
//            simpleMailMessage.setText(comtent);   //内容
//            simpleMailMessage.setTo("983022332@qq.com"); //接收者的邮箱
//            simpleMailMessage.setFrom(parentEmail);//发送者邮箱
//            javaMailSender.send(simpleMailMessage);
//
//        }

        return comments;
    }


    //删除评论
    @Override
    public void deleteComment(Comment comment, Long id) {
        commentDao.deleteComment(id);
        blogDao.getCommentCountById(comment.getBlogId());
    }

    @Override
    public Comment getEmailByParentId(Long parentId) {
        return commentDao.getEmailByParentId(parentId);
    }
//    @Async后的属性参数值是指定使用哪个线程池，这里我们自己配置一个线程池来让Async指定
    @Override
    public void sendMail(User user, Comment comment, HttpServletRequest request, HttpServletResponse response) throws MessagingException {
        String title = blogDao.getTitleById(comment.getBlogId()); //评论所在的博文标题

        if (user != null) {
            //如果是管理员发的评论
            if (comment.getParentComment().getId() == null) {
                //如果是根评论
                //不需要发给自己邮件
                return;
            } else {
                //如果不是根评论，则给[我回复的对象]发一封提醒邮件
                Comment parentComment = commentDao.getEmailByParentId(comment.getParentComment().getId());//获取父评论

                Mail mail = new Mail(null, parentComment.getEmail(), parentComment.getNickname(), parentComment.getContent(),
                        comment.getNickname(), comment.getContent(),
                        "/blog/" + comment.getBlogId(), "您在XiaoYang的博客《" + title + "》中的评论有了新的回复！");
                mailUtil.sendThymeleafEmail(mail);
            }
        } else {
            //如果不是管理员发的评论
            if (comment.getParentComment().getId() == -1) {
                //如果是根评论
                //发给我自己，提醒有人在留言板留言了
                Mail mail = new Mail(null, "983022332@qq.com", "小杨博主", null,
                        comment.getNickname(), comment.getContent(),
                        "/blog/" + comment.getBlogId(), "有新的访客在您的博客《" + title + "》中你有了新的评论！");
                mailUtil.sendThymeleafEmail(mail);

            }

            }
        }


    }

